<style scoped lang="less">
.areatree {
  border: 1px solid #7e7e7e51;
  max-height: 1rem;
  overflow: auto;
  .area-tree {
    height: 100% !important;
    padding: 0 !important;
  }
}
</style>
<template>
  <div class="record-new">
    <el-form ref="newForm" :model="newForm" label-width="150px">
      <el-form-item
        label="行政区域："
        v-if="region"
        prop="areaName"
        :rules="[
          { required: true, message: '请选择行政区域', trigger: 'change' },
        ]"
      >
        <div v-if="!areaShow" @click="areaShow = true" class="pointer">{{ regionName }}（点击选择）</div>
        <div class="areatree" v-else>
          <areaTree type="all" lastRegion :isEditable="false" @nodeClick="areaClickAction"></areaTree>
        </div>
      </el-form-item>
      <el-form-item label="行政区域：" v-else>
        {{
        newForm.areaName || areaNames.join(",")
        }}
      </el-form-item>
      <el-form-item
        label="企业名称："
        prop="name"
        :rules="[
          { required: true, message: '请输入企业名称', trigger: 'change' },
        ]"
      >
        <el-input placeholder="请输入" type="text" v-model.trim="newForm.name"></el-input>
      </el-form-item>
      <el-form-item label="企业代码：">
        <el-input placeholder="请输入" type="text" v-model.trim="newForm.enterpriseCode"></el-input>
      </el-form-item>
      <el-form-item
        label="坐标定位："
        prop="lat"
        :rules="[
          { required: true, message: '请输入经纬度', trigger: 'change' },
        ]"
      >
        <div class="flex">
          <div class="flex-1 mr-10">
            <el-input placeholder="经纬度" type="text" v-model.trim="coord"></el-input>
          </div>
          <div>
            <el-button type="green" @click="locateAction">定位</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item
        label="详细地址："
        prop="addr"
        :rules="[
          { required: true, message: '请输入详细地址', trigger: 'change' },
        ]"
      >
        <el-input placeholder="请输入" type="text" v-model.trim="newForm.addr"></el-input>
      </el-form-item>
      <el-form-item
        label="消防等级："
        prop="fireRating"
        :rules="[
          { required: true, message: '请选择消防等级', trigger: 'change' },
        ]"
      >
        <el-select
          class="full"
          v-model="newForm.fireRating"
          placeholder="请选择"
          @change="hanldIndustry"
        >
          <el-option :label="item.name" :value="item.id" v-for="item in levelList" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="单位类别："
        prop="unitCategory"
        :rules="[
          { required: true, message: '请选择单位类别', trigger: 'change' },
        ]"
      >
        <div class="flex">
          <div class="flex-1 mr-10">
            <el-input placeholder="请选择" type="text" v-model.trim="unitTypeName" readonly></el-input>
          </div>
          <div>
            <el-button type="green" native-type="button" @click="chooseUnitType">选择</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item
        label="高危企业："
        prop="isHighRisk"
        :rules="[
          { required: true, message: '请选择是否高危', trigger: 'change' },
        ]"
      >
        <el-radio-group v-model="newForm.isHighRisk">
          <el-radio label="1">是</el-radio>
          <el-radio label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="单位性质："
        prop="unitProperty"
        :rules="[
          { required: true, message: '请选择单位性质', trigger: 'change' },
        ]"
      >
        <el-select class="full" v-model="newForm.unitProperty" placeholder="请选择">
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item, index) in unitList"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="消防安全责任人："
        prop="oneResponPersonName"
        :rules="[
          { required: true, message: '请输入消防安全责任人姓名' },
          { validator: validateOneResponPerson, trigger: 'change' },
        ]"
      >
        <div class="flex">
          <div style="width: 40%" class="mr-10">
            <el-input placeholder="姓名" type="text" v-model.trim="newForm.oneResponPersonName"></el-input>
          </div>
          <div class="flex-1">
            <el-input placeholder="电话" type="text" v-model.trim="newForm.oneResponPersonPhone"></el-input>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="消防安全管理人：" prop="oneResponPersonName">
        <div class="flex">
          <div style="width: 40%" class="mr-10">
            <el-input placeholder="姓名" type="text" v-model.trim="newForm.safeManagePersonName"></el-input>
          </div>
          <div class="flex-1">
            <el-input placeholder="电话" type="text" v-model.trim="newForm.safeManagePersonPhone"></el-input>
          </div>
        </div>
      </el-form-item>
      <!-- <el-form-item label="消防安全负责人：" prop="safeResponPersonName" :rules="[{ required: true,message: '请输入消防安全负责人姓名'},{validator: validateSafeResponPerson, trigger: 'change' }]">
		  		<div class="flex">
		  			<div style="width: 40%" class="mr-10">
		  				<el-input placeholder="姓名" type="text" v-model.trim="newForm.safeResponPersonName"></el-input>
		  			</div>
		  			<div class="flex-1">
		  				<el-input placeholder="电话" type="text" v-model.trim="newForm.safeResponPersonPhone"></el-input>
		  			</div>
		  		</div>
		  	</el-form-item>
		  	<el-form-item label="消防安全管理人：" prop="safeManagePersonName" :rules="[{ required: true,message: '请输入消防安全管理人姓名'},{validator: validateSafeManagePerson, trigger: 'change' }]">
		  		<div class="flex">
		  			<div style="width: 40%" class="mr-10">
		  				<el-input placeholder="姓名" type="text" v-model.trim="newForm.safeManagePersonName"></el-input>
		  			</div>
		  			<div class="flex-1">
		  				<el-input placeholder="电话" type="text" v-model.trim="newForm.safeManagePersonPhone"></el-input>
		  			</div>
		  		</div>
      </el-form-item>-->
      <!-- 自定义管理人员 start -->
      <div class="flex mb-20">
        <div class="el-form-item__label" style="width:150px;">
          <el-button
            type="primary"
            native-type="button"
            :disabled="customState"
            @click="customMemberNameVisible = true"
          >自定义管理人员</el-button>
        </div>
        <div class="flex-1" v-if="customMemberNameVisible">
          <el-input
            class="mr-10"
            placeholder="请输入人员分类名称"
            type="text"
            v-model.trim="customMemberName"
            style="width:150px;"
          ></el-input>
          <el-button type="green" native-type="button" @click="confirmCustomMemberName">确定</el-button>
          <el-button type="cancel" native-type="button" @click="customMemberNameVisible = false">取消</el-button>
        </div>
      </div>
      <el-form-item :label="item.typeName + '：'" v-for="(item, index) in customMember" :key="index">
        <div class="flex">
          <div style="width: 40%" class="mr-10">
            <el-input placeholder="姓名" type="text" v-model.trim="item.personName"></el-input>
          </div>
          <div class="flex-1">
            <el-input placeholder="电话" type="text" v-model.trim="item.personPhone"></el-input>
          </div>
          <a class="ml-10" href="javascript:;" @click="deleteCustomMember(item, index)">删除</a>
        </div>
      </el-form-item>
      <!-- 自定义管理人员 end -->
      <!-- <el-form-item
        label="所属行业："
        prop="industry"
        :rules="[
          { required: true, message: '请选择所属行业', trigger: 'change' },
        ]"
      >
        <div class="flex">
          <div class="flex-1 mr-10">
            <el-input
              placeholder="请选择"
              type="text"
              v-model.trim="industryName"
              readonly
            ></el-input>
          </div>
          <div>
            <el-button type="green" native-type="button" @click="chooseIndustry"
              >选择</el-button
            >
          </div>
        </div>
      </el-form-item>-->

      <!-- <el-form-item label="消防主管部门：" prop="fireDepartmentId" :rules="[{ required: true, message: '请选择消防主管部门', trigger: 'change' }]">
		  		<div class="flex">
		  			<div class="flex-1 mr-10">
		  				<el-input placeholder="请选择" type="text" v-model.trim="fireDepartmentName" readonly></el-input>
		  			</div>
		  			<div>
		  				<el-button type="green" native-type="button" @click="chooseFireDepartment">选择</el-button>
		  			</div>
		  		</div>
		  	</el-form-item>
		  	<el-form-item label="行业主管部门：" prop="industryAuthoritiesId" :rules="[{ required: true, message: '请选择行业主管部门', trigger: 'change' }]">
		  		<div class="flex">
		  			<div class="flex-1 mr-10">
		  				<el-input placeholder="请选择" type="text" v-model.trim="industryAuthorityName" readonly></el-input>
		  			</div>
		  			<div>
		  				<el-button type="green" native-type="button" @click="chooseIndustryAuthority">选择</el-button>
		  			</div>
		  		</div>
      </el-form-item>-->
      <!-- <el-form-item v-if="activeData" label="机构：">
		  		<div class="flex">
		  			<div class="flex-1 mr-10">
		  				{{activeData.orgName}}
		  			</div>
		  		</div>
      </el-form-item>-->
      <el-form-item label="机构(默认本机构)：" v-if="type!=='fire'&&!region">
        <div class="flex">
          <div class="flex-1 mr-10">
            <el-input placeholder="请选择" type="text" v-model.trim="orgName" readonly></el-input>
          </div>
          <div>
            <el-button type="green" native-type="button" @click="chooseOrg">选择</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="邀请码：" v-if="region">
        <el-input placeholder="请输入" type="text" v-model.trim="newForm.enterpriseCode"></el-input>
      </el-form-item>
      <!--        <el-form-item label="续费：" prop="oneResponPersonName">
        <div class="flex">
          <div style="width: 40%" class="mr-10">
            <el-input placeholder="姓名" type="text" v-model.trim="newForm.oneResponPersonName"></el-input>
          </div>
          <div class="flex-1">
            <el-input placeholder="电话" type="text" v-model.trim="newForm.oneResponPersonPhone"></el-input>
          </div>
        </div>
      </el-form-item>-->
    </el-form>
    <!-- 定位 start -->
    <el-dialog
      :visible.sync="locationModalVisible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <h2 slot="title" class="fs-18">
        定位
        <small>（点击地图选点）</small>
      </h2>
      <Location
        v-if="locationModalVisible"
        ref="location"
        :coord="coord"
        :areaNames="areaList"
        @save="saveLocation"
        @cancel="locationModalVisible = false"
      ></Location>
    </el-dialog>
    <!-- 定位 end -->
    <!-- 行业 start -->
    <el-dialog
      v-if="industryModalVisible"
      title="行业列表"
      :visible.sync="industryModalVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <Industry
        ref="industry"
        :industryList="industryList"
        :industry="industry"
        @cancel="industryModalVisible = false"
      ></Industry>
      <div slot="footer">
        <el-button type="primary" @click="saveIndustry">提交</el-button>
      </div>
    </el-dialog>
    <!-- 行业 end -->
    <!-- 单位类别 start -->
    <el-dialog
      v-if="unitTypeModalVisible"
      title="单位类别列表"
      :visible.sync="unitTypeModalVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <UnitType
        ref="unitType"
        :unitType="unitType"
        @cancel="unitTypeModalVisible = false"
        :fireRatingId="newForm.fireRating"
      ></UnitType>
      <div slot="footer">
        <el-button type="primary" @click="saveUnitType">提交</el-button>
      </div>
    </el-dialog>
    <!-- 单位类别 end -->
    <!-- 消防主管部门 start -->
    <el-dialog
      v-if="fireDepartmentModalVisible"
      title="消防主管部门列表"
      :visible.sync="fireDepartmentModalVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <FireDepartment
        ref="fireDepartment"
        :fireDepartment="fireDepartment"
        @cancel="fireDepartmentModalVisible = false"
      ></FireDepartment>
      <div slot="footer">
        <el-button type="primary" @click="saveFireDepartment">提交</el-button>
      </div>
    </el-dialog>
    <!-- 消防主管部门 end -->
    <!-- 行业主管部门 start -->
    <el-dialog
      v-if="industryAuthorityModalVisible"
      title="行业主管部门列表"
      :visible.sync="industryAuthorityModalVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <IndustryAuthority
        ref="industryAuthority"
        :selectedData="industryAuthority"
        @cancel="industryAuthorityModalVisible = false"
      ></IndustryAuthority>
      <div slot="footer">
        <el-button type="primary" @click="saveIndustryAuthority">提交</el-button>
      </div>
    </el-dialog>
    <!-- 行业主管部门 end -->
    <!-- 机构 start -->
    <el-dialog
      v-if="orgModalVisible"
      title="机构列表"
      :visible.sync="orgModalVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <Org ref="org" :selectedData="org" @cancel="orgModalVisible = false"></Org>
      <div slot="footer">
        <el-button type="primary" @click="saveOrg">提交</el-button>
      </div>
    </el-dialog>
    <!-- 机构 end -->
  </div>
</template>
<script>
import { mapState } from "vuex";
import Location from "@/components/census/record/Location.vue";
import Industry from "@/components/census/record/Industry.vue";
import UnitType from "@/components/census/record/UnitType.vue";
import FireDepartment from "@/components/census/record/FireDepartment.vue";
import IndustryAuthority from "@/components/census/record/IndustryAuthority.vue";
import Org from "@/components/census/record/Org.vue";
import areaTree from "@/components/census/AreaTree.vue";
export default {
  name: "newRecord",
  components: {
    Location,
    Industry,
    UnitType,
    FireDepartment,
    IndustryAuthority,
    Org,
    areaTree
  },
  props: {
    region: {
      type: Boolean,
      default: false
    },
    activeData: {
      type: Object,
      default() {
        return null;
      }
    },
    area: {
      type: String,
      default: ""
    },
    areaNames: {
      type: Array,
      default() {
        return [];
      }
    },
    unitList: {
      type: Array,
      default() {
        return [];
      }
    },
    levelList: {
      type: Array,
      default() {
        return [];
      }
    },
    type: {
      type: String,
      default: ""
    }
    // industryList: {
    //   type: Array,
    //   default() {
    //     return [];
    //   },
    // },
  },
  computed: {
    coord() {
      if (this.newForm.lon) {
        return this.newForm.lon + "," + this.newForm.lat;
      }
    },
    industryName() {
      return this.industry ? this.industry.name : "";
    },
    unitTypeName() {
      return this.unitType ? this.unitType.name : "";
    },
    fireDepartmentName() {
      return this.fireDepartment ? this.fireDepartment.name : "";
    },
    industryAuthorityName() {
      return this.industryAuthority ? this.industryAuthority.name : "";
    },
    orgName() {
      return this.org ? this.org.name : "";
    }
  },
  watch: {
    activeData() {
      this.initForm();
    },
    customMember(val) {
      if (val.length == 4) {
        this.customState = true;
      } else {
        this.customState = false;
      }
    }
  },
  data() {
    return {
      newForm: {},
      loading: false,
      locationModalVisible: false,
      industry: null,
      industryModalVisible: false,
      unitType: null,
      unitTypeModalVisible: false,
      fireDepartment: null,
      fireDepartmentModalVisible: false,
      industryAuthority: null,
      industryAuthorityModalVisible: false,
      org: null,
      orgModalVisible: false,
      customMemberNameVisible: false,
      customMemberName: "",
      customMember: [],
      customState: false,
      industryList: [],
      fireRatingId: "",
      regionName: "",
      areaShow: false,
      activeAreaLevel: 0,
      areaList: []
    };
  },
  methods: {
    areaClickAction(data, level) {
      this.activeAreaLevel = level;
      if (this.activeAreaLevel < 5) {
        this.$message.error("请选择详细的行政区域");
        return;
      }
      this.regionName = this.newForm.areaName = data.allname;
      this.areaList = data.allname.split(",");
      this.newForm.area = data.id;
      this.areaShow = false;
    },
    hanldIndustry(e) {
      this.fireRatingId = e;
      console.log(this.fireRatingId);
    },
    validateOneResponPerson(rule, value, callback) {
      if (!this.newForm.oneResponPersonName) {
        return callback(new Error("请输入消防第一负责人姓名"));
      }
      if (!this.newForm.oneResponPersonPhone) {
        return callback(new Error("请输入消防第一负责人电话"));
      }
      callback();
    },
    validateSafeResponPerson(rule, value, callback) {
      if (!this.newForm.safeResponPersonName) {
        return callback(new Error("请输入消防安全负责人姓名"));
      }
      if (!this.newForm.safeResponPersonPhone) {
        return callback(new Error("请输入消防安全负责人电话"));
      }
      callback();
    },
    validateSafeManagePerson(rule, value, callback) {
      if (!this.newForm.safeManagePersonName) {
        return callback(new Error("请输入消防安全管理人姓名"));
      }
      if (!this.newForm.safeManagePersonPhone) {
        return callback(new Error("请输入消防安全管理人电话"));
      }
      callback();
    },
    initForm() {
      if (this.activeData) {
        this.newForm = this.utils.pick(this.activeData, [
          "id",
          "isDel",
          "area",
          "name",
          "lon",
          "lat",
          "addr",
          "fireRating",
          "enterpriseCode",
          "isHighRisk",
          "unitProperty",
          "oneResponPersonName",
          "oneResponPersonPhone",
          "safeResponPersonName",
          "safeResponPersonPhone",
          "safeManagePersonName",
          "safeManagePersonPhone",
          "industry",
          "unitCategory",
          "areaName",
          "fireDepartmentId",
          "industryAuthoritiesId"
        ]);
        this.newForm.isHighRisk = this.newForm.isHighRisk ? "1" : "0";
        this.newForm.isDel = this.newForm.isDel ? "1" : "0";
        this.customMember =
          this.activeData.businessCustomizeManagePersonList || [];
        this.industry = this.activeData.industry
          ? { id: this.activeData.industry, name: this.activeData.industryName }
          : null;
        this.unitType = this.activeData.unitCategory
          ? {
              id: this.activeData.unitCategory,
              name: this.activeData.unitCategoryName
            }
          : null;
        this.fireDepartment = this.activeData.fireDepartmentId
          ? {
              id: this.activeData.fireDepartmentId,
              name: this.activeData.fireDepartmentName
            }
          : null;
        this.industryAuthority = this.activeData.industryAuthoritiesId
          ? {
              id: this.activeData.industryAuthoritiesId,
              name: this.activeData.industryAuthoritiesName
            }
          : null;
        this.org = this.activeData.orgId
          ? { id: this.activeData.orgId, name: this.activeData.orgName }
          : null;
      } else {
        this.newForm = {
          area: this.area,
          name: "",
          lon: "",
          lat: "",
          addr: "",
          fireRating: "",
          enterpriseCode: "",
          isHighRisk: "1",
          unitProperty: "",
          oneResponPersonName: "",
          oneResponPersonPhone: "",
          safeResponPersonName: "",
          safeResponPersonPhone: "",
          safeManagePersonName: "",
          safeManagePersonPhone: "",
          persons: [],
          industry: "",
          unitCategory: ""
        };
        if (this.$refs["newForm"]) {
          this.$refs["newForm"].resetFields();
        }
      }
    },
    locateAction() {
      this.locationModalVisible = true;
    },
    saveLocation(coord) {
      this.$set(this.newForm, "lon", coord[0]);
      this.$set(this.newForm, "lat", coord[1]);
      this.locationModalVisible = false;
    },
    chooseIndustry() {
      this.industryModalVisible = true;
    },
    saveIndustry() {
      this.industry = this.$refs.industry.getSelected();
      if (!this.industry) {
        this.$message.error("请选择行业");
        return;
      }
      this.$set(this.newForm, "industry", this.industry.id);
      this.$refs.newForm.validateField("industry");
      this.industryModalVisible = false;
    },
    chooseUnitType() {
      console.log(this.newForm.fireRating);
      this.unitTypeModalVisible = true;
    },
    saveUnitType() {
      this.unitType = this.$refs.unitType.getSelected();
      if (!this.unitType) {
        this.$message.error("请选择单位类别");
        return;
      }
      this.$set(this.newForm, "unitCategory", this.unitType.id);
      this.$refs.newForm.validateField("unitCategory");
      this.unitTypeModalVisible = false;
    },
    chooseFireDepartment() {
      this.fireDepartmentModalVisible = true;
    },
    saveFireDepartment() {
      this.fireDepartment = this.$refs.fireDepartment.getSelected();
      if (!this.fireDepartment) {
        this.$message.error("请选择消防主管部门");
        return;
      }
      // this.newForm.fireDepartmentId = this.fireDepartment.id
      this.$set(this.newForm, "fireDepartmentId", this.fireDepartment.id);
      this.$refs.newForm.validateField("fireDepartmentId");
      this.fireDepartmentModalVisible = false;
    },
    chooseIndustryAuthority() {
      this.industryAuthorityModalVisible = true;
    },
    saveIndustryAuthority() {
      this.industryAuthority = this.$refs.industryAuthority.getSelected();
      if (!this.industryAuthority) {
        this.$message.error("请选择行业主管部门");
        return;
      }
      this.$set(
        this.newForm,
        "industryAuthoritiesId",
        this.industryAuthority.id
      );
      this.$refs.newForm.validateField("industryAuthoritiesId");
      // this.newForm.industryAuthoritiesId = this.industryAuthority.id
      this.industryAuthorityModalVisible = false;
    },
    chooseOrg() {
      this.orgModalVisible = true;
    },
    saveOrg() {
      this.org = this.$refs.org.getSelected();
      if (!this.org) {
        this.$message.error("请选择行业主管部门");
        return;
      }
      this.$set(this.newForm, "orgId", this.org.id);
      this.orgModalVisible = false;
    },
    confirmCustomMemberName() {
      if (!this.customMemberName) {
        this.$message.error("请输入人员分类名称");
        return;
      }
      this.customMemberNameVisible = false;
      this.customMember.push({
        typeName: this.customMemberName
      });
    },
    deleteCustomMember(item, index) {
      this.showConfirm("确定删除当前帐号？", () => {
        this.customMember.splice(index, 1);
        this.newForm.isDel = "1";
      });
    },
    submitAction() {
      this.$refs["newForm"].validate(valid => {
        if (valid) {
          this.$emit("submitting");
          this.loading = true;
          let persons = [];
          this.customMember.forEach(item => {
            let temp = {};
            temp[item.typeName] = [item.personName, item.personPhone];
            persons.push(temp);
          });
          let params = Object.assign({}, this.newForm);
          params.persons = persons;
          delete params.areaName;
          let url = params.id
            ? "/business/business/businessUpdate"
            : "/business/business/businessAdd";
          this.$ajax({
            url: url,
            method: "post",
            data: params
          }).then(
            data => {
              this.loading = false;
              this.$message({
                type: "success",
                message: "保存成功",
                center: true
              });
              this.$emit("success", data);
            },
            error => {
              this.$emit("fail");
              this.loading = false;
              this.$message.error(error.msg || "系统错误");
            }
          );
        } else {
          return false;
        }
      });
    }
  },
  created() {
    if (!this.region) {
      this.initForm();
      this.areaList = this.areaNames.join(',');
      console.log(this.areaNames.join(','),'this.areaList');
    }
  }
};
</script>
